package com.yexuejc.vertx.todolist.verticle;

import com.yexuejc.base.util.JsonUtil;
import com.yexuejc.vertx.todolist.entity.User;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.asyncsql.AsyncSQLClient;
import io.vertx.ext.sql.ResultSet;
import io.vertx.ext.sql.SQLConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @PackageName: com.yexuejc.vertx.todolist.verticle
 * @Description:
 * @author: maxf
 * @date: 2018/4/13 9:39
 */
public class DBVerticle {
    Logger logger = LoggerFactory.getLogger(DBVerticle.class);
    private AsyncSQLClient client;

    public DBVerticle(AsyncSQLClient client) {
        this.client = client;
    }

    public void getConn(SQLConnectionCallback callback) {
        client.getConnection(res -> {
            if (res.succeeded()) {
                callback.conn(res.result());
            } else {
                logger.error("数据库连接失败", res.cause());
            }
        });
    }

    public void getUser(SqlListCallback callback) {
        logger.info("查询数据库");
        System.out.println("查询数据库");
        getConn(conn -> {
            conn.query("SELECT * from tb_user", res -> {
                if (res.succeeded()) {
                    ResultSet rs = res.result();
                    logger.info(JsonUtil.obj2Json(rs));
                    List<User> list = new ArrayList<>();
                    for (JsonObject jsonObject : rs.getRows()) {
                        User user = JsonUtil.json2Obj(jsonObject.toString(), User.class);
                        list.add(user);
                    }
                    System.out.println(JsonUtil.obj2Json(list));
                    callback.list(list, list.size());
                } else {
                    logger.error("查询失败", res.cause());
                }
            });
        });
    }

    interface SQLConnectionCallback {
        void conn(SQLConnection sqlConnection);

    }

    public interface SqlListCallback {
        void list(List<User> list, int count);

    }

    public interface SqlBeanCallback {
        void user(User user);
    }
}
